package pkg

import (
	"encoding/json"
	"fmt"
	"github.com/oschwald/geoip2-golang"
	"io/ioutil"
	"net"
	"net/http"
)

// 获取外网ip地址
func GetLocation(ip, key string) string {
	if ip == "127.0.0.1" || ip == "localhost" {
		return "内部IP"
	}
	url := "https://restapi.amap.com/v5/ip?ip=" + ip + "&type=4&key=" + key
	fmt.Println("url", url)
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("restapi.amap.com failed:", err)
		return "未知位置"
	}
	defer resp.Body.Close()
	s, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(s))

	m := make(map[string]string)

	err = json.Unmarshal(s, &m)
	if err != nil {
		fmt.Println("Umarshal failed:", err)
	}
	//if m["province"] == "" {
	//	return "未知位置"
	//}
	return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
}

// 获取局域网ip地址
func GetLocaHonst() string {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println("net.Interfaces failed, err:", err.Error())
	}

	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()

			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						return ipnet.IP.String()
					}
				}
			}
		}

	}
	return ""
}

func GetIpLocation(ipStr string) (string, error) {
	db, err := geoip2.Open("lib/GeoLite2-City.mmdb")
	if err != nil {
		return "", err
	}
	defer func() {
		recover()
		db.Close()
	}()
	ip := net.ParseIP(ipStr)
	record, err := db.City(ip)
	if err != nil {
		return "", err
	}
	name := ""
	contry := ""
	if record.Country.Names != nil && record.Country.Names["zh-CN"] != "" {
		contry = record.Country.Names["zh-CN"]
	} else {
		if record.RegisteredCountry.Names != nil && record.RegisteredCountry.Names["zh-CN"] != "" {
			contry = record.Country.Names["zh-CN"]
		}
	}
	name += contry
	if record.Subdivisions != nil && len(record.Subdivisions) > 0 && record.Subdivisions[0].Names != nil && record.Subdivisions[0].Names["zh-CN"] != "" {
		name += record.Subdivisions[0].Names["zh-CN"]
	}

	if record.City.Names != nil && record.City.Names["zh-CN"] != "" {
		name += record.City.Names["zh-CN"]
	}
	if name == "" {
		name = "unknown"
	}
	return name, nil
}
